<template>
    <view>
        <view class="content">
            <block>

                <!-- 登录 -->
                <view class="form-content">
                    <form @submit="formLogin">
                        <!-- 账号密码 -->
                        <block>
                            <input type="text" v-model="userName" placeholder="请输入账号" maxlength="60" name="accounts" class="form-item margin-vertical-main wh-auto">
                            <input type="text" v-model="password" placeholder="请输入密码" minlength="6" maxlength="18" name="pwd" password="true" class="form-item margin-vertical-main wh-auto">
                        </block>
						<!-- 协议 -->
                        <view class="margin-top-xxxl cr-gray">
                            <view class="dis-inline-block va-m" @tap="agreement_change">
                                <radio-group class="dis-inline-block va-m" style="transform:scale(0.6)">
                                    <label>
                                        <radio value="agreement" color="#20a53a" :checked="agreement_status" />
                                    </label>
                                </radio-group>
                            </view>
                            <view class="dis-inline-block va-m">
                               阅读并同意 《<text class="cr-main" @tap="agreement_event" data-value="userregister">服务协议</text>》 与 《<text class="cr-main" @tap="agreement_event" data-value="userprivacy">隐私政策</text>》
                            </view>
                        </view>

						<view class="margin-top-xxxl cr-gray">
						    <view class="dis-inline-block va-m" @tap="bindAccound_change">
						        <radio-group class="dis-inline-block va-m" style="transform:scale(0.6)">
						            <label>
						                <radio value="agreement" color="#20a53a" :checked="bingAccount_status" />
						            </label>
						        </radio-group>
						    </view>
						    <view class="dis-inline-block va-m">
						       记住账号密码
						    </view>
						</view>

						<button class="bg-main br-main cr-white round text-size margin-top-xxxl" form-type="submit" type="default" hover-class="none" :loading="form_submit_loading" :disabled="form_submit_loading">登录</button>

						<!-- #ifdef MP-WEIXIN || MP-TOUTIAO -->
						<!-- <button class="bg-green br-green cr-white round text-size margin-top-xxxl" type="default" @tap="get_user_info_event">一键登录</button> -->
						<!-- #endif -->
                    </form>
                </view>

            </block>
        </view>

		<component-popup :propShow="popup_status" propPosition="bottom" @onclose="closePopup">

					    <view class="emoji-popup bg-white">
							<span>请选择账套</span>
					        <view class="close fr oh">
					            <view class="fr" @tap.stop="closePopup">
					                <uni-icons type="clear" size="46rpx" color="#999"></uni-icons>
					            </view>
					        </view>
							<view class="emoji-popup-content oh tc"  v-for="(item,index) in popupList" :key="index" @click="choice(item)" :style="[{animationDelay: '0.1s'}]">
							  <view class="content" style="padding-top: 4%;" >
							    <text class="cuIcon-favorfill text-yellow"></text>
							    <text class="text-grey">{{item.name}}({{item.code}})</text>
							  </view>
							</view>
							<view style="height: 50px;"></view>
					    </view>

		</component-popup>


    </view>
</template>
<script>
    const app = getApp();
    import base64 from '../../common/js/lib/base64.js';
	    import componentPopup from "../../components/popup/popup";

    export default {
        data() {
            return {
				temtUser:[],
				popup_status:false,
				userName: '',
				password: '',//Hao@123456
				popupTitle:"",//
				popupList:[],//客户或供应商或车队列表
				userIdentity:'',//用户角色 客户或供应商或车队
                params: null,
                user: null,
                prev_page: null,
                form_input_mobile_value: '',
                form_input_email_value: '',
                form_input_accounts_value: '',
                form_input_image_verify_value: '',
                verify_submit_text: '获取验证码',
                verify_loading: false,
                verify_disabled: false,
                form_submit_loading: false,
                verify_time_total: 60,
                temp_clear_time: null,
                agreement_status: false,
				bingAccount_status: false,
                verify_image_url: null,
                popup_image_verify_status: false,
                // 基础配置
				is_refreshed_base_data: 0,
				is_exist_base_data: 0,
                common_user_onekey_bind_mobile_list: [],
                home_site_logo_square: null,
                home_user_login_type: [],
                home_user_reg_type: [],
                home_user_login_img_verify_state: 0,
                home_user_register_img_verify_state: 0,
                common_img_verify_state: 0,
                client_value: app.globalData.application_client_type(),
                // 0 确认绑定方式, 1 验证码绑定
                current_login_bind_type: 0,
                // 当前操作方式
                current_opt_form: 'auth',
                current_opt_type: 'auth',
                current_opt_type_title: {
                    auth: "授权用户信息",
                    bind: "绑定手机",
                    login_username: "账号密码登录",
                    login_sms: "手机验证码登录",
                    login_email: "邮箱验证码登录",
                    reg_username: "账号密码注册",
                    reg_sms: "手机验证码注册",
                    reg_email: "邮箱验证码注册",
                    forget: "密码找回",
                    success: "登录成功",
                },
                // 第三方登录
                plugins_thirdpartylogin_data: null,
                plugins_thirdpartylogin_user: null,
                // 错误提示信息
                error_msg: null,
            };
        },

		components: {
		    componentPopup
		},

        // 页面加载初始化
        onLoad(params) {
            this.setData({
                params: params
            });

            // 上一个页面记录
            var page = app.globalData.prev_page();
            if(page != null && page != 'pages/login/login') {
                uni.setStorageSync(app.globalData.data.cache_prev_page_key, page);
            }

			this.userName = wx.getStorageSync("userName");
			this.password = wx.getStorageSync("password");

            // 数据初始化
            this.init();
        },
        methods: {
			//
			selectRole(popupList,user){
				console.log("popupList---------",popupList.length);
				if(popupList.length > 1){
					this.temtUser =user;
					this.popup_status =true;
				}else{
					user.role = popupList[0];
					uni.setStorageSync(app.globalData.data.cache_user_info_key,user);
					var page = uni.getStorageSync(app.globalData.data.cache_prev_page_key) || null;
					if(page != null) {
					    this.setData({prev_page: page});
					    setTimeout(function() {
					        app.globalData.url_open('/'+page, true);
					    }, 2000);
					}
				}
			},
			//选择账套
			choice(e){
				console.log("e",e);
				this.temtUser.role =e;
				uni.setStorageSync(app.globalData.data.cache_user_info_key,this.temtUser);

				var page = uni.getStorageSync(app.globalData.data.cache_prev_page_key) || null;
				if(page != null) {
				    this.setData({prev_page: page});
				    setTimeout(function() {
				        app.globalData.url_open('/'+page, true);
				    }, 2000);
				}
			},
			//关闭选择账套弹框
			closePopup(){
			      this.popup_status =false;
			},
            // 数据初始化
            init() {
                // 缓存初始化配置
                this.init_config(true);

                // 用户信息
                var user = app.globalData.get_user_cache_info();

                // 数据处理
                var type = (user == null) ? 'auth' : 'bind';
                var form = type;
				var is_base = (this.home_site_logo_square || null) != null ? 1 : 0;
                // #ifdef H5 || APP
                if(user == null) {
                    // 非小程序：如果开启登录则取第一个登录方式
                    if((this.home_user_login_type || null) != null && this.home_user_login_type.length > 0) {
						form = 'login';
						// 开启登录则取第一个
						type = 'login_'+this.home_user_login_type[0];

						// 用户登录和验证码获取开启图片验证码
						if(this.home_user_login_img_verify_state == 1 || this.common_img_verify_state == 1) {
							this.image_verify_event('user_login');
						}
                    } else {
						is_base = 0;
					}
                } else {
                    // 是否需要绑定手机
                    if (type == 'bind' && !app.globalData.user_is_need_login(user)) {
                        type = 'bind';
                        form = 'success';
                    }
                }
                // #endif
                uni.setNavigationBarTitle({
                    title: this.current_opt_type_title[type]
                });

                // 是否参数指定类型和表单
                if((this.params.opt_type || null) != null)
                {
                    type = this.params.opt_type;
                }
                if((this.params.opt_form || null) != null)
                {
                    form = this.params.opt_form;
                }

                this.setData({
                    user: user,
                    current_opt_type: type,
                    current_opt_form: form,
					is_exist_base_data: is_base,
					is_refreshed_base_data: 1,
                });

                // 登录成功
                if(this.current_opt_form == 'success') {
                    var page = uni.getStorageSync(app.globalData.data.cache_prev_page_key) || null;
                    if(page != null) {
                        this.setData({prev_page: page});
                        setTimeout(function() {
                            app.globalData.url_open('/'+page, true);
                        }, 2000);
                    }
                }
            },

            // 初始化配置
            init_config(status) {
                if ((status || false) == true) {
                    this.setData({
						home_site_logo_square: app.globalData.get_config('config.home_site_logo_square'),
                        common_user_onekey_bind_mobile_list: app.globalData.get_config('config.common_user_onekey_bind_mobile_list', []),
                        home_user_login_type: app.globalData.get_config('config.home_user_login_type'),
                        home_user_reg_type: app.globalData.get_config('config.home_user_reg_type'),
                        home_user_login_img_verify_state: app.globalData.get_config('config.home_user_login_img_verify_state'),
                        home_user_register_img_verify_state: app.globalData.get_config('config.home_user_register_img_verify_state'),
                        common_img_verify_state: app.globalData.get_config('config.common_img_verify_state'),
                        plugins_thirdpartylogin_config: app.globalData.get_config('plugins_base.thirdpartylogin.data'),
                        plugins_thirdpartylogin_data: app.globalData.get_config('plugins_thirdpartylogin_data')
                    });
                } else {
                    app.globalData.is_config(this, 'init_config');
                }
            },

            // 登录授权事件
            get_user_info_event(e) {
				// 网络请求
				uni.showLoading({
				    title: '处理中...'
				});
                // #ifdef MP-WEIXIN
                uni.getUserProfile({
                    desc: '用于完善会员资料',
                    lang: 'zh_CN',
                    success: (res) => {
						console.log("uni.getUserProfile---res",res)
						const {errMsg, userInfo} = res
						console.log("errMsg:",errMsg);
						if(errMsg !== "getUserProfile:ok") {
						  uni.showModal({
						    title: '提示',
						    content: '您取消了授权登录，请重新授权',
						    showCancel: false
						  })
						  return
						}else{
							uni.login({
							  success: res => {
							    console.log("uni.login---res:",res);
							    let loginParams = {
							      code:res.code,
							      wechatname:userInfo.nickName,
							      avatarurl:userInfo.avatarUrl,
							      sex:userInfo.gender,
							      city:userInfo.city
							    }
								console.log("loginParams:",loginParams);
								uni.request({
								    url: app.globalData.get_request_url('weChatAccountLogin'),
								    method: 'POST',
								    data: loginParams,
								    dataType: 'json',
								    success: res => {
										this.form_submit_loading =false;
										// console.log("bingWeChatAccount---res:",res);
										// console.log("bingWeChatAccount---res:",res.data.success);
										if(res.data.success){
											  if(res.data.code === 200){
													//登录成功
													uni.showToast({title:res.data.message,duration:2000})
													//console.log("res",res.data.result);
													console.log("res",res.data.result.user);

													//选择客户
													let userIdentity =res.data.result.user.userIdentity;
													console.log("userIdentity=",userIdentity);
													if(userIdentity === 5){

													}
													else if(userIdentity >= 2){
														let phone =res.data.result.user.phone;
														if(phone){
															this.popupList =res.data.result.user.userIdentityList;
															if(this.popupList.length === 0){
																uni.showToast({title: "空的客户信息。", icon: "error", duration: 8000})
															}else{
																this.selectRole(this.popupList,res.data.result.user);
															}

														}else{
															uni.showToast({title: "当前账号的手机号为空，请先联系管理员登记手机号码。", icon: "none", duration: 8000})
														}
													}else{
														uni.showToast({title: "当前账号的身份为普通用户，限制登录APP端。如需登录，请联系管理员分配权限。", icon: "none", duration: 8000})
													}

											  }else{
													app.globalData.showToast(res.data.message);
											  }
										}else{
											app.globalData.showToast(res.data.message);
										}
									},
									fail: () => {
										app.globalData.showToast('服务器请求出错');
									}
								});
							},
							fail: () => {
							  uni.showToast({
							    title: "您取消了授权",
							    icon: "none",
							    duration: 2000
							  })
							},
							});
						}
                    }
                });
                // #endif
            },
            // 用户授权登录
            // auth_data  授权数据
            user_auth_code(auth_data) {
                if ((auth_data || null) != null) {
                    app.globalData.user_auth_login(this, 'user_auth_back_event', null, auth_data);
                } else {
                    app.globalData.showToast("授权失败");
                }
            },

            // 授权返回事件
            user_auth_back_event() {
                var user = app.globalData.get_user_cache_info();
                this.setData({
                    user: user
                });

                // 是否需要绑定手机号码
                if (app.globalData.user_is_need_login(user) == false) {
                    uni.navigateBack();
                }

                // 初始化
                this.init();
            },


            // 登录表单提交
            formLogin(e) {
                // 是否已同意协议
                if(!this.agreement_status) {
                    app.globalData.showToast('请先同意协议');
                    return false;
                }
                // 数据验证
                var validation = [];
                if(!this.userName || this.userName.length===0){
                    uni.showToast({title: '请输入用户名',icon:'error'});
                    return;
                }
                if(!this.password || this.password.length===0){
					uni.showToast({title: '请输入密码',icon:'error'});
					return;
                }
                if (app.globalData.fields_check(e.detail.value, validation)) {
                    // 登录方式
                    e.detail.value['type'] = this.current_opt_type.replace('login_', '');

                    // #ifdef MP
                    // 小程序数据
                    var client_type = app.globalData.application_client_type();
                    if((this.user || null) != null) {
                        var field_openid = client_type+'_openid';
                        var field_unionid = client_type+'_unionid';
                        e.detail.value[field_openid] = this.user[field_openid] || '';
                        e.detail.value[field_unionid] = this.user[field_unionid] || '';
                    } else {
                        var login_data = app.globalData.get_login_cache_info();
                        if(login_data != null) {
                            var field_openid = client_type+'_openid';
                            var field_unionid = client_type+'_unionid';
                            e.detail.value[field_openid] = login_data['openid'] || '';
                            e.detail.value[field_unionid] = login_data['unionid'] || '';
                        }
                    }
                    // #endif

                    // 网络请求
                    uni.showLoading({
                        title: '登录中...'
                    });
                    this.setData({
                        form_submit_loading: true
                    });

					//不绑定微信号
					e.detail.value['bind']="2";
					uni.request({
						    url: app.globalData.get_request_url('appLogin'),
						    method: 'POST',
						    data: e.detail.value,
						    dataType: 'json',
						    success: res => {
								uni.hideLoading();
								this.form_submit_loading =false;
								console.log("res",res);
								if (res.data.code == 0) {
									//登录成功
									uni.showToast({title:res.data.msg,duration:2000})
									//记住账号密码
									if(this.bingAccount_status){
										wx.setStorageSync("userName",this.userName);
										wx.setStorageSync("password",this.password);
									}
									//选择客户
									let userIdentity =res.data.data.userIdentity;
									console.log("userIdentity222=",userIdentity);
									if(userIdentity >= 2){
										let phone =res.data.data.phone;
										if(phone){
											this.popupList =res.data.data.userIdentityList;
											if(this.popupList.length === 0){
												uni.showToast({title: "空的客户信息。", icon: "error", duration: 8000})
											}else{
												this.selectRole(this.popupList,res.data.data);
											}

										}else{
											uni.showToast({title: "当前账号的手机号为空，请先联系管理员登记手机号码。", icon: "none", duration: 8000})
										}
									}else{
										uni.showToast({title: "当前账号的身份为普通用户，限制登录APP端。如需登录，请联系管理员分配权限。", icon: "none", duration: 8000})
									}
								}else{
									console.log("res",res)
									uni.showToast({title:"账号或密码错误。", icon: "error", duration: 8000})
								}

						    },
						    fail: () => {
						        uni.hideLoading();
						        this.setData({
						            form_submit_loading: false
						        });
						        app.globalData.showToast('服务器请求出错');
						    }
						});
                }
            },

            // 登录和注册成功回调处理
            user_success_handle(res) {
                if (res.data.code == 0 && (res.data.data || null) != null) {
                    // 清除定时任务并存储用户信息
                    clearInterval(this.temp_clear_time);
                    uni.setStorageSync(app.globalData.data.cache_user_info_key, res.data.data);

                    // 是否强制绑定账号处理
                    if((this.plugins_thirdpartylogin_user || null) != null && (this.plugins_thirdpartylogin_user.is_force_bind_user || 0) == 1) {
                        uni.request({
                            url: app.globalData.get_request_url('bind', 'index', 'thirdpartylogin'),
                            method: 'POST',
                            data: this.plugins_thirdpartylogin_user,
                            dataType: 'json',
                            success: res => {
                                if(res.data.code == 0) {
                                    uni.hideLoading();
                                    uni.setStorageSync(app.globalData.data.cache_user_info_key, res.data.data);
                                    this.success_back_handle(res);
                                } else {
                                    uni.hideLoading();
                                    this.setData({
                                        form_submit_loading: false
                                    });
                                    app.globalData.showToast(res.data.msg);
                                }
                            },
                            fail: () => {
                                uni.hideLoading();
                                this.setData({
                                    form_submit_loading: false
                                });
                                app.globalData.showToast('服务器请求出错');
                            }
                        });
                    } else {
                        uni.hideLoading();
                        this.success_back_handle(res);
                    }
                } else {
                    uni.hideLoading();
                    this.setData({
                        form_submit_loading: false
                    });
                    app.globalData.showToast(res.data.msg);
                }
            },

            // 成功后处理
            success_back_handle(res) {
                var self = this;
                app.globalData.showToast(res.data.msg, 'success');
                var event_callback = this.params.event_callback || null;
                setTimeout(function() {
                    var pages = getCurrentPages();
                    if(pages.length > 1) {
                        // 触发回调函数
                        if (event_callback != null) {
                            if((pages[pages.length-2][event_callback] || null) != null) {
                                pages[pages.length-2][event_callback]();
                            }
                        }
                        // 默认返回上一页
                        uni.navigateBack();
                    } else {
                        // 仅一个页面则执行成功返回
                        self.success_event();
                    }
                }, 1000);
            },

            // 协议事件
            agreement_event(e) {
                var value = e.currentTarget.dataset.value || null;
                if (value == null) {
                    app.globalData.showToast('协议类型有误');
                    return false;
                }

                // 是否存在协议 url 地址
                var key = 'agreement_' + value + '_url';
                var url = app.globalData.get_config('config.' + key) || null;
                if (url == null) {
                    app.globalData.showToast('协议url地址有误');
                    return false;
                }

                // 打开 webview
                app.globalData.open_web_view(url);
            },

            // 协议改变
            agreement_change(e) {
                this.setData({
                    agreement_status: !this.agreement_status
                });
            },
			bindAccound_change(e) {
			    this.setData({
			        bingAccount_status: !this.bingAccount_status
			    });
			},

            // 表单类型事件
            opt_form_event(e) {
                var value = e.currentTarget.dataset.value;
                // 手机更换绑定来源则直接返回
                if(value == 'bind' && (this.params.opt_form || null) != null && this.params.opt_form == 'bind_verify') {
                    uni.navigateBack();
                }

                // 设置数据
                var data = {
                    current_opt_form: value
                };

                // 小程序使用授权自动登录
                // 切换手机绑定方式
                if(value == 'auth' || value == 'bind') {
                    data['current_opt_type'] = value;
                }

                // 密码找回同时设置表单类型
                if(value == 'forget') {
                    data['current_opt_type'] = 'forget';
                    if(this.common_img_verify_state == 1) {
                        this.image_verify_event('user_forget');
                    }
                }

                // 开启登录则取第一个
                if(value == 'login' && this.home_user_login_type.length > 0) {
					data['current_opt_type'] = 'login_'+this.home_user_login_type[0];
					// 是否开启图片验证码
					if(this.home_user_login_img_verify_state == 1 || this.common_img_verify_state == 1) {
						this.image_verify_event('user_login');
					}
                }

                // 开启注册则取第一个
                if(value == 'reg' && this.home_user_reg_type.length > 0) {
					data['current_opt_type'] = 'reg_'+this.home_user_reg_type[0];
					// 是否开启图片验证码
					if(this.home_user_register_img_verify_state == 1 || this.common_img_verify_state == 1) {
						this.image_verify_event('user_reg');
					}
                }
                this.setData(data);

                // 标题
                if((data.current_opt_type || null) != null) {
                    uni.setNavigationBarTitle({
                        title: this.current_opt_type_title[data.current_opt_type]
                    });
                }
            },

            // 操作类型事件
            opt_type_event(e) {
                var value = e.currentTarget.dataset.value || null;
                if(value != null) {
                    this.setData({
                        current_opt_type: value
                    });

                    // 图片验证码
                    if(value == 'login_username' && this.home_user_login_img_verify_state == 1) {
                        this.image_verify_event('user_login');
                    }
                    if((value == 'login_sms' || value == 'login_email') && this.common_img_verify_state == 1) {
                        this.image_verify_event('user_login');
                    }
                    if(value == 'reg_username' && this.home_user_register_img_verify_state == 1) {
                        this.image_verify_event('user_reg');
                    }
                    if((value == 'reg_sms' || value == 'reg_email') && this.common_img_verify_state == 1) {
                        this.image_verify_event('user_reg');
                    }

                    // 标题
                    uni.setNavigationBarTitle({
                        title: this.current_opt_type_title[value]
                    });
                }
            },

            // 图片验证码事件
            image_verify_event(e) {
                var type = (typeof e == 'string') ? e : e.currentTarget.dataset.type || null;
                if(type !== null) {
                    var tv = app.globalData.get_timestamp();
                    var url = app.globalData.get_request_url('userverifyentry', 'user', '', 'type='+type+'&t='+tv);
                    this.setData({
                        verify_image_url: url
                    });
                }
            },

            // 缓存数据刷新
            cache_refresh_event(e) {
                app.globalData.init_config();
                var self = this;
                uni.showLoading({
                    title: '加载中...'
                });
                setTimeout(function() {
                    self.init();
                    uni.hideLoading();
                }, 3000);
            },

            // 第三方登录事件
            plugins_thirdpartylogin_event(e) {
                // 是否已同意协议
                if(!this.agreement_status) {
                    app.globalData.showToast('请先同意协议');
                    return false;
                }
                // 直接跳转到登录地址、这里还可以根据终端类型进行处理业务逻辑
                var type = e.currentTarget.dataset.type || null;
                var url = e.currentTarget.dataset.url || null;
                window.location.href = url;
            },

            // 第三方登录绑定账号取消
            plugins_thirdpartylogin_cancel_event(e) {
                uni.redirectTo({
                    url: '/pages/login/login'
                });
            },

            // 成功返回
            success_event(e) {
                var url = (this.prev_page == null) ? app.globalData.data.tabbar_pages[0] : this.prev_page;
                app.globalData.url_open(url, true);
            }
        }
    };
</script>
<style>
    @import './login.css';
</style>
<style>
    .emoji-popup {
        padding: 20rpx 10rpx 0 10rpx;
        position: relative;
		height: 300px;
    }
    .emoji-popup .close {
        position: absolute;
        top: 20rpx;
        right: 20rpx;
        z-index: 2;
    }
    .emoji-popup-content {
        max-height: 50vh;
        overflow-y: scroll;
        overflow-x: hidden;
        margin-top: 4rpx;
    }
    .emoji-popup-content .emoji-item {
        height: 80rpx;
        line-height: 80rpx;
    }

	.popupContent {
	    padding-top: 8%;
	}
	.popupContent .icon {
	    width: 180rpx;
	    height: 180rpx !important;
	}
</style>
